<!-- 
    手机验证码组件PhoneCode设计
    1. 界面效果 
         - 显示发送验证码按钮
         - 切换倒计时按钮
            实现思路: 
               定义布尔变量isSend=true
    2. 倒计时实现
        - 定义初始时间变量timer=60
        - 循环定时器
        - 一次性定时器记录时间 60秒未输入自动重置
 -->
<template>
	<el-button @click="bindSendCode">{{ isSendCode ? timer : '获取验证码' }}</el-button>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'
const emits = defineEmits(['getVeryCode'])
const props = defineProps<{ phone: string }>()
const timer = ref<string>('10')
const isSendCode = ref<boolean>(false)
const bindSendCode = () => {
	if (props.phone === '') {
		ElMessage({
			message: '手机号不能为空!',
			type: 'error'
		})
		return
	}
	timer.value = '10'
	isSendCode.value = true
	computedTimer()
	emits('getVeryCode')
}
let interval: any = null
const computedTimer = () => {
	interval = setInterval(() => {
		let sendTime = Number(timer.value)
		sendTime--
		timer.value = sendTime < 10 ? '0' + sendTime : sendTime + ''
	}, 1000)
}

watch(timer, () => {
	if (Number(timer.value) <= 0) {
		clearInterval(interval)
		isSendCode.value = false
	}
})
</script>

<style scoped lang="scss">
.el-button {
	margin: 5px 0px;
	width: 200px;
}
</style>
